package com.jxwifi.cloud.quickclean.welcome;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.basicactivity.BasicActivity;
import com.bumptech.glide.Glide;
import com.jxwifi.cloud.quickclean.MainActivity;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.LocationGaoDe;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.login.LoginActivity;
import com.jxwifi.cloud.quickclean.login.UserloginActivity;
import com.jxwifi.cloud.quickclean.main.MainUserActivity;
import com.jxwifi.cloud.quickclean.popwindow.PopProtocol;
import com.jxwifi.cloud.quickclean.utils.NetUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WelcomeActivity extends ClientBasicActivity implements WCView {

    private WCPresenter mPresenter;


    @Bind(R.id.welcome_images)
    ImageView mWelcomeImages;
    @Bind(R.id.layout_skip)
    LinearLayout ll_skip;
    @Bind(R.id.tv_second)
    TextView tv_time;
    private TimeCount time;
    int jumpLoginCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //下面的这个判断是用来解决应用程序在第一次安装成功点击打开后，再点击home键回到桌面后再点击程序出现重新启动的问题
        // （还需要注意的一点是在onDestroy方法中不能写finsh()和System.exit(0)方法要不然程序或出现短时间的黑屏）
        if((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0){
            finish();
            return;
        }
        setContentView(R.layout.activity_welome);
        ButterKnife.bind(this);
        if (LocationGaoDe.getLatitude() == 0.0) {
            new LocationGaoDe().init(getApplicationContext());
            LocationGaoDe.startLocation();
        }
        mPresenter=new WCPresenter(mBaseContext,this);
        mPresenter.initHeadLayout();
        /*if (NetUtils.isConnected(this)) {
            mPresenter.initAdvert();
        }*/
        //mPresenter.getPersimmions();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        /*测试机型：Redmi Note 4X安卓版本：7.0 MIUI版本：5-V10.3.2.0.NCFCNXM 无法启动，报错
        android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running
        问题原因：PopupWindow弹窗不能直接在Activity的onCreate函数里执行，必须要等activity的生命周期函数全部执行完毕之后，需要依附的View加载完成了才可以。
        解决方案：在public void onWindowFocusChanged(boolean hasFocus){}函数中调用，或单独开启一个线程去调用*/
        if(hasFocus){
            mPresenter.getPersimmions();
        }
    }

    @Override
    public Window getVindow() {
        return getWindow();
    }

    @Override
    public void getjump() {
        if (mPresenter.popwindow!=null && mPresenter.popwindow.isShowing()){
            mPresenter.popwindow.dismiss();
        }
        Log.i(TAG,"getjump() ==> mPresenter.imageUrl = "+mPresenter.imageUrl);
        /*if(null == mPresenter.imageUrl){
            toNextAc();
        }else{*/
            mWelcomeImages.setVisibility(View.VISIBLE);
            ll_skip.setVisibility(View.VISIBLE);
            mWelcomeImages.setImageResource(R.mipmap.icon_welcome_images2);
            //Glide.with(this).load(mPresenter.imageUrl).into(mWelcomeImages);
            time = new TimeCount(3000, 1000);
            time.start();
        //}

    }


    public void toNextAc(){
        if(time != null){
            time.cancel();
            Log.i(TAG,"toNextAc() ==> 移除倒计时对象");
        }
        if (AccountMgr.isLogin(mBaseContext)){
            Intent intent = new Intent();
            intent.setClass(mBaseContext,MainActivity.class);
            startActivity(intent);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);//处理广告页中的启动动画，添加这个可以去掉系统的默认加载动画
            finish();
        }else{
            Intent intent = new Intent();
            intent.setClass(mBaseContext,LoginActivity.class);
            startActivity(intent);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);//处理广告页中的启动动画，添加这个可以去掉系统的默认加载动画
            finish();
        }
    }

    @Override
    public void getrequestPermissions(String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions, requestCode);
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPresenter.onRequestPermissionsResult();
    }

    @Override
    public ImageView getWelcomeImages() {
        return mWelcomeImages;
    }


    @Override
    public void onFailure(int errorCode, String msg) {

    }

    @Override
    public LinearLayout getll() {
        return ll_skip;
    }

    @Override
    public TextView getTx() {
        return tv_time;
    }

    /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            // ap_mode_add.setText("重新验证");
            // ap_mode_add.setClickable(true);
            if(jumpLoginCount == 0){
                jumpLoginCount++;
                toNextAc();
            }

        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            //ap_mode_add.setText(getString(R.string.ap_config_success) + " "+ millisUntilFinished / 1000 + "秒");
            int pro = (int) (millisUntilFinished / 1000);
            Log.i(TAG, "计时开始 ==> ap_progress=" + pro);
            // ap_progress==12
            tv_time.setText(pro+"");

        }
    }

    @OnClick({R.id.welcome_images, R.id.layout_skip})
    void clickCK(View v) {
        switch (v.getId()) {
            //点击广告图片跳到详情页
            case R.id.welcome_images:
                /*time.cancel();
                Intent intent = new Intent();
                intent.setClass(mBaseContext, MainUserActivity.class);
                intent.putExtra("agreementId", 3 + "");
                intent.putExtra("title", mPresenter.title);
                intent.putExtra("positionUrl", mPresenter.positionUrl);
                startActivity(intent);*/
                break;
            //跳过
            case R.id.layout_skip:
                time.onFinish();
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.i(TAG,"onResume() ==>");
    }
}
